package com.rain.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class DateUtil {
    private static final Object lockObj = new Object();
    private static Map<String, ThreadLocal<SimpleDateFormat>> stringThreadLocalMap = new HashMap<>();

    private static SimpleDateFormat getSimpleDateFormat(final String pattern){
        ThreadLocal<SimpleDateFormat> threadLocal = stringThreadLocalMap.get(pattern);
        if(threadLocal == null) {
            synchronized (lockObj){
                threadLocal = stringThreadLocalMap.get(pattern);
                if(threadLocal == null) { // 双重检查
                    threadLocal = new ThreadLocal<SimpleDateFormat>(){
                        @Override
                        protected SimpleDateFormat initialValue() {
                            return new SimpleDateFormat(pattern);
                        }
                    };
                    stringThreadLocalMap.put(pattern,threadLocal);
                }
            }
        }
        return threadLocal.get();
    }

    public static String format(Date date,String pattern){
        if (date == null) {
            return null; // 或者 return "";
        }
        return getSimpleDateFormat(pattern).format(date);
    }

    public static Date parse(String dateStr, String pattern){
        try{
            return getSimpleDateFormat(pattern).parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}
